package com.hmsm.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hmsm.server.util.QueryResult;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.bean.LocalUser;
import com.hmsm.sys.po.RoleInfo;
import com.hmsm.sys.service.RoleInfoService;

@Controller
public class RoleController {

	public static String MANAGED_ORG_LIST = "managedOrgList";
	
	public static String JSON = "json";
	
	@Resource
	private RoleInfoService roleInfoService;

	public RoleInfoService getRoleInfoService() {
		return roleInfoService;
	}

	public void setRoleInfoService(RoleInfoService roleInfoService) {
		this.roleInfoService = roleInfoService;
	}

	@RequestMapping("/roleInfo-manage")
	public ModelAndView manage(Integer orgId, String name, String nowpage, String maxpage, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		
		try {
			List<LocalDept> manageOrgList = getRoleInfoService().getManageOrgList(currentUser);
			QueryResult<RoleInfo> result = getRoleInfoService().manage(orgId, name, nowpage, maxpage, currentUser);
			modelAndView.getModel().put("result", result);
			Map<Integer, Boolean> editMap = new HashMap<Integer, Boolean>();
			Map<Integer, Boolean> userAuthMap = new HashMap<Integer, Boolean>();
			List<RoleInfo> list = new ArrayList();
			for(RoleInfo roleInfo:result.getResultlist()){
				boolean haveManageRange = getRoleInfoService().haveManageRight(roleInfo, currentUser);
				boolean userAuth = getRoleInfoService().haveUserAuthRight(roleInfo, currentUser);
				editMap.put(roleInfo.getPkId(), haveManageRange);
				userAuthMap.put(roleInfo.getPkId(), userAuth);
				if(userAuth){
					list.add(roleInfo);
				}
			}
			result.setResultlist(list);
			modelAndView.getModel().put("Edit", editMap);
			modelAndView.getModel().put("UserAuth", userAuthMap);
			modelAndView.getModel().put(MANAGED_ORG_LIST, manageOrgList);
		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.setViewName("error");
		}
		
		
		return modelAndView;
	}

	@RequestMapping("/roleInfo-add")
	public ModelAndView add(Integer orgId, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		
		try {
			List<LocalDept> manageOrgList = getRoleInfoService().getManageOrgList(currentUser);
			boolean isAdmin = currentUser.isSysAdmin();
			RoleInfo roleInfo;
			String funcStr = null;
			List<LocalUser> userList;
			roleInfo = new RoleInfo();
			roleInfo.setPkId(0);
			roleInfo.setOrgId(0);
			roleInfo.setState(1);
			if(!isAdmin||currentUser.getDepart()!=null&&currentUser.getDepart().getOrgId()!=null){
				roleInfo.setOrgId(currentUser.getDepart().getOrgId());
			}else{
				if(orgId!=null){
					roleInfo.setOrgId(orgId);
				}
			}
			userList = new ArrayList<LocalUser>();
			modelAndView.getModel().put("role", roleInfo);
			modelAndView.getModel().put(MANAGED_ORG_LIST, manageOrgList);
			modelAndView.getModel().put("isAdmin", isAdmin);
			
			LinkedHashMap<Map<String, Object>,List<Map<String, Object>>> rightMap = getRoleInfoService().getMenu();
			modelAndView.getModel().put("rightMap", rightMap);
			
			modelAndView.getModel().put("funcStr", funcStr);
			String managedFuncStr = getRoleInfoService().getManagedFuncArray(roleInfo, currentUser);
			modelAndView.getModel().put("managedFuncStr", managedFuncStr);

			modelAndView.getModel().put("userList", userList);

		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.getModel().put("errorMessage", "发生错误："+e.getMessage());
			modelAndView.setViewName("error");
		}
		
		return modelAndView;
	}

	@RequestMapping("/roleInfo-edit")
	public ModelAndView edit(Integer roleId, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		
		try {
			List<LocalDept> manageOrgList = getRoleInfoService().getManageOrgList(currentUser);
			Map<Integer, LocalDept> managedOrgs = getRoleInfoService().getManagedOrgs(currentUser);
			boolean isAdmin = currentUser.isSysAdmin();
			RoleInfo roleInfo;
			String funcStr = null;
			String managedFuncStr = null;
			List<LocalUser> userList;
			if(roleId==null||roleId==0){
				roleInfo = new RoleInfo();
				roleInfo.setPkId(0);
				roleInfo.setState(1);
				if(!isAdmin||currentUser.getDepart()!=null&&currentUser.getDepart().getOrgId()!=null){
					roleInfo.setOrgId(currentUser.getDepart().getOrgId());
				}
				userList = new ArrayList<LocalUser>();
			}else{
				roleInfo = (RoleInfo) getRoleInfoService().edit(roleId, currentUser);
				funcStr = getRoleInfoService().getRoleFuncArray(roleId);
				managedFuncStr = getRoleInfoService().getManagedFuncArray(roleInfo, currentUser);
				userList = getRoleInfoService().getRoleUsers(roleId, managedOrgs==null?null:managedOrgs.keySet());
			}
			modelAndView.getModel().put("role", roleInfo);
			modelAndView.getModel().put(MANAGED_ORG_LIST, manageOrgList);
			modelAndView.getModel().put("isAdmin", isAdmin);
			
			LinkedHashMap<Map<String, Object>,List<Map<String, Object>>> rightMap = getRoleInfoService().getMenu();
			modelAndView.getModel().put("rightMap", rightMap);
			
			modelAndView.getModel().put("funcStr", funcStr);
			modelAndView.getModel().put("managedFuncStr", managedFuncStr);

			modelAndView.getModel().put("userList", userList);

		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.getModel().put("errorMessage", "发生错误："+e.getMessage());
			modelAndView.setViewName("error");
		}
		
		return modelAndView;
	}

	public ModelAndView saveRoleUsers(int roleId, String removeUserIds, String addUserIds, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		try {
			if (removeUserIds!=null){
				String[] userIdList =  removeUserIds.split(",");
				for(String userIdStr:userIdList){
					if(userIdStr.length()>0){
						getRoleInfoService().getRoleInfoService().unbindUserRoleRelation(roleId, Integer.parseInt(userIdStr));
					}
				}
			}
			if (addUserIds!=null){
				String[] userIdList =  addUserIds.split(",");
				for(String userIdStr:userIdList){
					if(userIdStr.length()>0){
						getRoleInfoService().bindUserRoleRelation(Integer.parseInt(userIdStr), roleId);
					}
				}
			}
//			CommonUtil.userFuncMap = getRoleInfoService().initUserFunc();
		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.getModel().put("errorMessage", "发生错误："+e);
			modelAndView.setViewName("error");
		}
		
		return modelAndView;
	}

	public ModelAndView saveRoleFunc(int roleId, String name, String remark, Integer orgId, List<Integer> funcIds, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView(JSON);
		
		RoleInfo role = new RoleInfo();
		if (roleId>0){
			role.setPkId(roleId);
		}
		if(name==null){
			String errorMessage = "角色名称不能为空！";
			modelAndView.getModel().put("errorMessage", errorMessage);
			modelAndView.setViewName("");
		}
		role.setOrgId(orgId);//管理员选择传递过来的机构ID
		role.setName(name);
		role.setRemark(remark);
		role.setState(1);//1有效 2无效
		try {
			role = getRoleInfoService().save(role, currentUser);
			roleId=role.getPkId();
			getRoleInfoService().saveRoleFuncs(roleId, funcIds, currentUser);
			modelAndView.getModel().put("success", true);
		} catch (Exception e) {
			modelAndView.getModel().put("errorMessage", e.getMessage());
			modelAndView.getModel().put("success", false);
		}
		
		return modelAndView;
	}

	public ModelAndView save(RoleInfo role, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		
		try {
			role = getRoleInfoService().save(role, currentUser);
		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.getModel().put("errorMessage", "发生错误："+e);
			modelAndView.setViewName("error");
		}
		modelAndView.getModel().put("role", role);

		return modelAndView;
	}

	public ModelAndView del(int roleId, LocalUser currentUser, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("success");
		
		try {
			getRoleInfoService().delete(roleId, currentUser);
		} catch (Exception e) {
			String errorMessage = e.getMessage();
			modelAndView.getModel().put("errorMessage", errorMessage);
			modelAndView.setViewName("error");
		}
		
		return modelAndView;
	}
	
}
